
#include <iostream>
#include <stdlib.h>
#include <fstream>

#include "../common/Argv.h"
#include "../common/ArchivoIni.h"
#include "../common/StringUtils.h"
#include "../logger/logger.h"
#include "../IPC/ClientSocket.h"
#include "../IPC/ServerSocket.h"
#include "../channel_common/ChannelCommon.h"
#include "../IPC/Sequence.h"
#include "../IPC/ProcessAux.h"

int main(int argc, char **argv)
{
	CLogger::create("Servidor Entrada Broker");
	char buffer[TAM_BUFFER];
	int puertoEntrada = 0;
	// socket conectado al cliente
	ipc::ServerSocket socketEntradaPasivo;

	//Toma argumentos (main)
	Argv args(argv);

	if (args.getArgc() != 2)
	{
		std::cout <<"Servidor Entrada Broker Error: Cantidad de parametros invalida."<<std::endl;
		exit(1);
	}

	std::string brokerName= args.getArg(1);
	
	MapaIni config = ArchivoIni::parsearComoIni("brokers.ini");

	if(config[brokerName] == "")
	{
		CLogger::log("Broker configuration not found in brokers.ini",LogLevelEnum::FATAL);
		exit(1);
	}

	std::vector<std::string> brokerParams= StringUtils::splitString(config[brokerName],'|');

	if(brokerParams.size()<4)
	{
		CLogger::log("Malformed params",LogLevelEnum::FATAL);
		exit(1);
	}

	puertoEntrada = StringUtils::StringToNumber<int>(brokerParams[2]);
	
	CLogger::log("Levantando server: en puerto entrada:"+StringUtils::NumberToString(puertoEntrada) ,
			LogLevelEnum::INFO);

	socketEntradaPasivo.listen(puertoEntrada,1);
	
	CLogger::log("Se hizo el open pasivo, socket:"+
			StringUtils::NumberToString(puertoEntrada) ,LogLevelEnum::INFO);

	while (true)
	{
		ipc::ClientSocket socketEntrada(socketEntradaPasivo.accept());

		Argv channelArgs;
		channelArgs.pushArg(StringUtils::NumberToString(socketEntrada.getFd()));
		channelArgs.pushArg(brokerName);

		ProcessAux::launchProcess("./out/channel_in_broker",1,channelArgs.getArgv());

		socketEntrada.close();
	}
	return 0;
} 
